<?php

namespace app\common\model;


use think\Model;

class Comment extends Model
{
    // 表名
    protected $name = 'comment';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $common_where = [
        'status'=>1,
        'deletetime'=>null
    ];
    //无限极评论
    public function getList($where=[],$pid=0)
    {
        $commentModel = new \app\common\model\Comment();
        $where['pid']=$pid;
        $list  = $commentModel
            ->alias('c')
            ->join('User ui','ui.id = c.to_user_id','left')
            ->join('User u','u.id = c.user_id','left')
            ->field('c.*,u.nickname cname,u.avatar cavatar,ui.nickname rname')
            ->order('c.createtime desc')
            ->where($where)
            ->select();
        $list=json_decode(json_encode($list),true);
        foreach($list as $k=>&$v){
            //查询子回复
            $v['child'] = $this->getList($where,$v["id"]);
        }
        return $list;
    }

    public function getOne($where)
    {
        $info = Comment::alias('c')->where($where)
            ->join('user u','c.user_id = u.id','left')
            ->field('c.*,u.nickname cname,u.avatar')
            ->find();
        return $info;
    }
    public function reply(){
        return $this->hasMany('reply','comment_id','id');
    }

    public function formUser(){
        return $this->hasOne('user','id','user_id')->bind('avatar,nickname');
    }
    public function getAidList($where=[],$is_page=true,$limit=10)
    {
        if($is_page){
            $info =\app\common\model\Comment
                ::alias('c')
                ->with(['reply','formUser','reply'=>['user','toUser']])
                ->where($where)
                ->field('c.*')
                ->join('reply r', 'r.comment_id=c.id', 'left')
                ->group('c.id')
                ->paginate($limit);
        }else{
            $info =\app\common\model\Comment
                ::alias('c')
                ->with(['reply','formUser','reply'=>['user','toUser']])
                ->where($where)
                ->field('c.*')
                ->join('reply r', 'r.comment_id=c.id', 'left')
                ->group('c.id')
                ->limit($limit)
                ->select();
        }
        return $info;
    }
}